//
//  MoviePlayerViewController.m
//  OpenYourEyes
//
//  Created by 沈振烨 on 15/8/11.
//  Copyright (c) 2015年 沈振烨. All rights reserved.
//

#import "MoviePlayerViewController.h"
//#import <MediaPlayer/MediaPlayer.h>
#import "MoviePlayerView.h"
#import <AVFoundation/AVFoundation.h>
#import "FMDB.h"


@interface MoviePlayerViewController ()


@property (nonatomic, strong) MoviePlayerView *moviePlayerView;
@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, assign) BOOL isFirstTap;  //  是否第一次点击
@property (nonatomic, strong) UIProgressView *progress;// 播放进度

@property (nonatomic, assign, readonly) NSUInteger currentTime;  // 当前播放时间

@property (nonatomic, assign, readonly) NSUInteger totalTime;   // 总时长

@property (nonatomic, strong) NSTimer *paintingTimer;

@property (nonatomic, strong)FMDatabase *db; //  数据库表



@end

@implementation MoviePlayerViewController

//  用于移除观察者
- (void)dealloc
{

    [[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    [self removeObserverFromPlayerItem:self.player.currentItem];
    NSLog(@"被释放掉了");
    
}

- (void)loadView
{
    //  添加播放界面
    _moviePlayerView = [[MoviePlayerView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.view = _moviePlayerView;
    self.view.backgroundColor = [UIColor blackColor];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
//    //  添加播放界面
//    _moviePlayerView = [[MoviePlayerView alloc] initWithFrame:[UIScreen mainScreen].bounds];
//    [self.view addSubview:_moviePlayerView];
//    self.view.backgroundColor = [UIColor blackColor];
    
    NSString *urlStr = _model.playUrl;
    urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url=[NSURL URLWithString:urlStr];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    _player = [AVPlayer playerWithPlayerItem:playerItem];
    [self addProgressObserver];
    [self addObserverToPlayerItem:playerItem];
    
    
    
    
    [self createPlayer];
    [self dismissAllViews];
    [self writeToPath];
    
}

// 创建播放
- (void)createPlayer
{
    //  注册通知中心用来观察是否播放完毕
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(moviePlayFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
    // 创建播放器层
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    // 设置playerLayer的frame
    CGRect frame = self.view.bounds;
    frame.size.height = self.view.bounds.size.width;
    frame.size.width = self.view.bounds.size.height;
    playerLayer.frame = frame;
    //视频填充模式(没明白作用)
//    playerLayer.videoGravity=AVLayerVideoGravityResizeAspect;
    // 将播放器层添加到view的最下面
    [self.view.layer insertSublayer:playerLayer atIndex:0];
    _moviePlayerView.titleLabel.text = _model.title;
    
    //  播放界面添加轻拍手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissAllViews:)];
    [self.view addGestureRecognizer:tap];
    
    
    // 屏幕中心播放按钮添加点击事件
    [self.moviePlayerView.playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    //  播放界面返回添加点击事件
    [self.moviePlayerView.returnButton addTarget:self action:@selector(stopMoviePlayToBack:) forControlEvents:UIControlEventTouchUpInside];
    
    //  播放进度滑竿添加滑动时间
    [self.moviePlayerView.movieSlider addTarget:self action:@selector(movieSliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    
    //  给音量的滑杆设置事件
    [self.moviePlayerView.voiceSlider addTarget:self action:@selector(voiceSliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    
    //  给增大音量按钮添加点击事件
    [self.moviePlayerView.addVoiceButton addTarget:self action:@selector(doTapAddVoiceValue:) forControlEvents:UIControlEventTouchUpInside];
    
    //  给减小音量按钮添加点击时间
    [self.moviePlayerView.reduceVoiceButton addTarget:self action:@selector(doTapReduceVoiceValue:) forControlEvents:UIControlEventTouchUpInside];
    
    // 给缓存下载添加点击事件
    [self.moviePlayerView.downloadButton addTarget:self action:@selector(download:) forControlEvents:UIControlEventTouchUpInside];
    
//    //  给分享添加点击事件
//    [self.moviePlayerView.shareButton addTarget:self action:@selector(doTapToShare:) forControlEvents:UIControlEventTouchUpInside];
    
    //  给收藏添加点击事件
    [self.moviePlayerView.collectionButton addTarget:self action:@selector(doTapToCollection:) forControlEvents:UIControlEventTouchUpInside];
    
}


////  初始化播放器,播放器对象
//- (AVPlayer *)player
//{
//    
//    if (_player == nil) {
//        NSString *urlStr = _model.playUrl;
//        urlStr =[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//        NSURL *url=[NSURL URLWithString:urlStr];
//        AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
//        self.player = [AVPlayer playerWithPlayerItem:playerItem];
//        [self addProgressObserver];
//        [self addObserverToPlayerItem:playerItem];
//    }
//    return _player;
//}

// 点击播放或者暂停
- (void)playButtonAction:(UIButton *)sender
{
    //  rate 是player的一个属性,判断是暂停还是播放
    if(self.player.rate==0)
    { //暂停状态
        [sender setImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateNormal];
        [self.player play];
    }else if(self.player.rate==1)
    {//正在播放
        [self.player pause];
        [sender setImage:[UIImage imageNamed:@"bofang-1"] forState:UIControlStateNormal];
    }
}

// 点击缓存,将视频缓存到本地
- (void)download:(UIButton *)sender
{
    NSString *downloadPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"Download.db"];
    NSLog(@"downloadPath:%@",downloadPath);
    _db = [FMDatabase databaseWithPath:downloadPath];
    if ([_db open]) {
        NSLog(@"数据库打开失败");
        return;
    }
    
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS Download (Category text, CoverBlurred text, CoverForDetail text, CoverForFeed text, CoverForSharing text, Date integer, Description text, Duration integer, ID integer,Idx integer, PlayUrl text, RawWebUrl text, Title text, WebUrl text)"];
    
    //  将model存储到数据库中
    
    NSNumber *duration = [NSNumber numberWithInteger:_model.duration];
    NSNumber *ID = [NSNumber numberWithInteger:_model.ID];
    NSNumber *idx = [NSNumber numberWithInteger:_model.idx];
    NSNumber *date = [NSNumber numberWithInteger:_model.date];
    
    [_db executeUpdate:@"INSERT INTO Download (Category, CoverBlurred,CoverForDetail,CoverForFeed,CoverForSharing,Date,Description,Duration,ID,Idx,PlayUrl,RawWebUrl,Title,WebUrl) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",_model.category,_model.coverBlurred,_model.coverForDetail,_model.coverForFeed,_model.coverForSharing,date,_model.Description,duration,ID,idx,_model.playUrl,_model.rawWebUrl,_model.title,_model.webUrl];
    
}


// 点击收藏,收藏本视频 将本视频的相关信息写入数据库中
- (void)doTapToCollection:(UIButton *)sender
{

    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"Collection.db"];
    NSLog(@"%@",path);
    _db = [FMDatabase databaseWithPath:path];
    if (![_db open]) {
        NSLog(@"数据库打开失败");
        return;
    }
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS Collection (Category text, CoverBlurred text, CoverForDetail text, CoverForFeed text, CoverForSharing text, Date integer, Description text, Duration integer, ID integer,Idx integer, PlayUrl text, RawWebUrl text, Title text, WebUrl text)"];
    
    //  将model存储到数据库中
    
    NSNumber *duration = [NSNumber numberWithInteger:_model.duration];
    NSNumber *ID = [NSNumber numberWithInteger:_model.ID];
    NSNumber *idx = [NSNumber numberWithInteger:_model.idx];
    NSNumber *date = [NSNumber numberWithInteger:_model.date];
    
    [_db executeUpdate:@"INSERT INTO Collection (Category, CoverBlurred,CoverForDetail,CoverForFeed,CoverForSharing,Date,Description,Duration,ID,Idx,PlayUrl,RawWebUrl,Title,WebUrl) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",_model.category,_model.coverBlurred,_model.coverForDetail,_model.coverForFeed,_model.coverForSharing,date,_model.Description,duration,ID,idx,_model.playUrl,_model.rawWebUrl,_model.title,_model.webUrl];
    
}

//  点击返回,回到详情页面
- (void)stopMoviePlayToBack:(UIButton *)sender
{
    [self dismissViewControllerAnimated:NO completion:^{
//        [self.player pause];
//        self.player = nil;
//        [self.player seekToTime:CMTimeMake(0, 1)];
    }];
    NSLog(@"您点击了返回");
}



//  滑动滑轮改变声音的大小
- (void)voiceSliderValueChanged:(UISlider *)sender
{
    [_player setVolume:sender.value];
}

//  增大音量
- (void)doTapAddVoiceValue:(UIButton *)sender
{
    CGFloat a = _moviePlayerView.voiceSlider.value;
    a = a + 0.1;
    if (a >= 1) {
        a = 1;
    }
    _moviePlayerView.voiceSlider.value = a;
    [_player setVolume:a];
}

//  减小音量
- (void)doTapReduceVoiceValue:(UIButton *)sender
{
    CGFloat a = _moviePlayerView.voiceSlider.value;
    a = a - 0.1;
    if (a <= 0) {
        a = 0;
    }
    _moviePlayerView.voiceSlider.value = a;
    [_player setVolume:a];
}

//  第一次进入子视图是消失状态
- (void)dismissAllViews
{
    _moviePlayerView.topView.frame = CGRectMake(0, -55, self.view.bounds.size.width, 55);
    _moviePlayerView.bottomView.frame = CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, 50);
    _moviePlayerView.centerView.alpha = 0;
}


//  手势的点击事件,子视图消失或者出现
- (void)dismissAllViews:(UITapGestureRecognizer *)tap
{
    //  防止循环引用
    __weak typeof(self) myself = self;
    if (!self.isFirstTap)
    {
        [UIView animateWithDuration:0.2 animations:^{
            
            myself.moviePlayerView.topView.frame = CGRectMake(0, 0, myself.view.bounds.size.width, 55);
            myself.moviePlayerView.bottomView.frame = CGRectMake(0, myself.view.bounds.size.height - 50, myself.view.bounds.size.width, 50);
            myself.moviePlayerView.centerView.alpha = 0.6;
            
                        myself.isFirstTap = YES;
            
        }];
    } else
    {
        
        [UIView animateWithDuration:0.2 animations:^{
            myself.moviePlayerView.topView.frame = CGRectMake(0, -55, myself.view.bounds.size.width, 55);
            myself.moviePlayerView.bottomView.frame = CGRectMake(0, myself.view.bounds.size.height, myself.view.bounds.size.width, 50);
            myself.moviePlayerView.centerView.alpha = 0;

            myself.isFirstTap = NO;
        }];
        
    }
    
    [self createNSTimer];
    
}

//  定义一个NSTimer
- (void)createNSTimer
{
    self.paintingTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(paint:) userInfo:nil repeats:NO];
}


// 定时器执行的方法
- (void)paint:(NSTimer *)paramTimer
{
    self.moviePlayerView.topView.frame = CGRectMake(0, -55, self.view.bounds.size.width, 55);
    self.moviePlayerView.bottomView.frame = CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, 50);
    self.moviePlayerView.centerView.alpha = 0;
    self.isFirstTap = NO;
    [self stopPainting];
    
}

// 停止定时器
- (void) stopPainting{
    if (self.paintingTimer != nil){
        // 定时器调用invalidate后，就会自动执行release方法。不需要在显示的调用release方法
        [self.paintingTimer invalidate];
    }
}


//  视频播放完成, 状态为暂停状态
- (void)moviePlayFinished:(NSNotification *)notification
{
    NSLog(@"视屏播放完成");
}

// 给播放器添加进度更新
-(void)addProgressObserver{
    AVPlayerItem *playerItem=self.player.currentItem;
    UIProgressView *progress=self.progress;
    
    __weak typeof(self) myself = self;
    
    //这里设置每秒执行一次
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float current=CMTimeGetSeconds(time);
        float total=CMTimeGetSeconds([playerItem duration]);
        
        //  添加当前时间
        NSUInteger currentTime = playerItem.currentTime.value / playerItem.currentTime.timescale;
        _currentTime = currentTime;
        myself.moviePlayerView.currentTimeLabel.text = [NSString stringWithFormat:@"%.2lu:%.2lu",currentTime / 60,currentTime % 60];
        
        myself.moviePlayerView.movieSlider.minimumValue = 0.0;
        myself.moviePlayerView.movieSlider.maximumValue = myself.totalTime;
        myself.moviePlayerView.movieSlider.value = myself.currentTime;
        
        if (current) {
            [progress setProgress:(current/total) animated:YES];
        }
    }];
}

-(void)addObserverToPlayerItem:(AVPlayerItem *)playerItem{
    //监控状态属性，注意AVPlayer也有一个status属性，通过监控它的status也可以获得播放状态
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    //监控网络加载情况属性
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}



//  观察者的事件
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    AVPlayerItem *playerItem=object;
    if ([keyPath isEqualToString:@"status"])
    {
        AVPlayerStatus status= [[change objectForKey:@"new"] intValue];
        if(status==AVPlayerStatusReadyToPlay){
            NSLog(@"正在播放...，视频总长度:%.2f",CMTimeGetSeconds(playerItem.duration));
            // 添加总时间
            NSUInteger totalTime = playerItem.duration.value / playerItem.duration.timescale;
            _totalTime = totalTime;
            _moviePlayerView.totalTimeLabel.text = [NSString stringWithFormat:@"%.2lu:%.2lu",totalTime / 60,totalTime % 60];
    
        }
    }else if([keyPath isEqualToString:@"loadedTimeRanges"])
    {
        NSArray *array=playerItem.loadedTimeRanges;
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓冲时间范围
        float startSeconds = CMTimeGetSeconds(timeRange.start);
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);
        NSTimeInterval totalBuffer = startSeconds + durationSeconds;//缓冲总长度
        _moviePlayerView.progressView.progress = totalBuffer / _totalTime;
        _moviePlayerView.progressView.progressTintColor = [UIColor whiteColor];
        
        
        NSLog(@"共缓冲：%.2f",totalBuffer);
        
    }
}

//  移除观察者
-(void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem{
    [playerItem removeObserver:self forKeyPath:@"status"];
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}

//  滑动滑竿改变播放进度
- (void)movieSliderValueChanged:(UISlider *)sender
{
    __weak AVPlayer *myPlayer = self.player;
    if (self.player.rate == 0)
    {
        CMTime currentTime = CMTimeMake(sender.value, 1);
        [self.player seekToTime:currentTime];

    }
    if (self.player.rate == 1) {
        // 先暂停
        [self.player pause];
        CMTime currentTime = CMTimeMake(sender.value, 1);
        [self.player seekToTime:currentTime completionHandler:^(BOOL finished) {
            [myPlayer play];
        }];
    }
}


//  进入该视图控制器自动横屏进行播放
- (BOOL)shouldAutorotate
{
    [_moviePlayerView.playButton setImage:[UIImage imageNamed:@"zanting"] forState:UIControlStateNormal];
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskLandscape;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationLandscapeLeft;
}


// 创建协议txt格式,用户协议,视频功能声明,版权举报
- (void)writeToPath
{
    // 把数据写入到fy.txt中.
    // 1.数据
    NSString *userProtocolText = @"用户协议";
    NSString *movieFunctionText = @"视频功能声明";
    NSString *coprReportText = @"版权举报";
    // 2.userProtocol.txt
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *userProtocolPath = [documentPath stringByAppendingString:@"/userProtocol.txt"];
//    NSLog(@"userProtocolPath:%@",userProtocolPath);
    // 3.写入
    [userProtocolText writeToFile:userProtocolPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    // 创建 视频功能声明txt
    NSString *movieFunctionPath = [documentPath stringByAppendingString:@"/movieFunction.txt"];
//    NSLog(@"movieFunctionPath:%@",movieFunctionPath);
    // 3.写入
    [movieFunctionText writeToFile:movieFunctionPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    
    // 创建版权举报
    NSString *coprReportPath = [documentPath stringByAppendingString:@"/coprReport.txt"];
//    NSLog(@"coprReportPath:%@",coprReportPath);
    // 3.写入
    [coprReportText writeToFile:coprReportPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}

- (void)readFromPath
{
    //  读取用户协议
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *userProtocolPath = [documentPath stringByAppendingPathComponent:@"userProtocol.txt"];
    // 2.获取内容
    NSString *text = [NSString stringWithContentsOfFile:userProtocolPath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"%@",text);
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
